package com.example.shirospring.config;

import com.example.shirospring.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Configuration
public class ShiroConfig {
    @Resource
    private MyRealm myRealm;

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        // 1.创建defaultWebSecurityManager对象
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        // 2.创建加密对象，设置相关属性
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        // 2.1采用MD5加密
        matcher.setHashAlgorithmName("MD5");
        // 2.2迭代次数
        matcher.setHashIterations(3);

        // 3.将加密对象存储到myRealm中
        myRealm.setCredentialsMatcher(matcher);

        // 4.将myRealm存入defaultWebSecurityManager中
        defaultWebSecurityManager.setRealm(myRealm);

        // 5.设置remremberMe
        defaultWebSecurityManager.setRememberMeManager(rememberMeManager());

        // 6.返回
        return defaultWebSecurityManager;
    }

    /**
     * cookie属性设置
     *
     * @return
     */
    public SimpleCookie rememberMeCookie() {
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        // 设置跨域
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(30 * 24 * 60 * 60);
        return cookie;
    }

    /**
     * 创建shiro的cookie管理对象
     *
     * @return
     */
    public CookieRememberMeManager rememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        cookieRememberMeManager.setCipherKey("1234567890987654".getBytes(StandardCharsets.UTF_8));
        return cookieRememberMeManager;
    }

    /**
     * 配置shiro内置过滤器拦截范围
     *
     * @return
     */
    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();

        // 设置不认证就可以访问的资源
        definition.addPathDefinition("/user/login", "anon");

        // 设置需要认证才能访问的资源
        definition.addPathDefinition("/**", "authc");

        return definition;
    }
}
